﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Controllers;
using AVISOutBound.SSOServer.Payment;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AVISOutBound.SSOServer.Web.Controllers
{
    /// <summary>
    /// 支付单
    /// </summary>
    [Route("api/[controller]")]
    public class PayOrderController:AbpController
    {
        private IAlipayManager _alipayManager;
        private IWechatManager _wechatManager;
        private IPayOrderAppService _payOrderAppService;

        public PayOrderController(IAlipayManager alipayManager,IWechatManager wechatManager,IPayOrderAppService payOrderAppService)
        {
            _alipayManager = alipayManager;
            _wechatManager = wechatManager;

            _payOrderAppService = payOrderAppService;
        }

        /// <summary>
        /// 支付宝支付的回调
        /// </summary>
        /// <returns></returns>
        [HttpPost("alipaynotify"),AllowAnonymous]
        public async Task<HttpResponseMessage> AlipayNotify()
        {
            var receive = this._alipayManager.ParseNotify(HttpContext);
            Logger.Debug($"支付宝支付回调：\n商家单号：{receive.OutTradeNo}，支付宝交易凭证号：{receive.TradeNo}，是否成功：{receive.IsSuccess}");
            var result = await this._payOrderAppService.FinishPay(receive);
            Logger.Debug($"支付结果处理：{result}");
            return result ? new HttpResponseMessage() { Content = new StringContent("success") }
                : new HttpResponseMessage() { Content = new StringContent("fail") };
        }

        /// <summary>
        /// 微信支付的回调
        /// </summary>
        /// <returns></returns>
        [HttpPost("wechatpaynotify"),AllowAnonymous]
        public async Task<HttpResponseMessage> WechatPayNotify()
        {
            var receive = this._wechatManager.ParseNotify(HttpContext);
            Logger.Debug($"微信支付回调：\n商家单号：{receive.OutTradeNo}，微信支付交易号：{receive.TradeNo}，是否成功：{receive.IsSuccess}");
            var result = await this._payOrderAppService.WechatFinishPay(receive);
            Logger.Debug($"支付结果处理：{result}");
            return result ? new HttpResponseMessage() { Content = new StringContent("success") }
                : new HttpResponseMessage() { Content = new StringContent("fail") };
        }
    }
}
